package com.toptime.cloudhelper.consumer;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Slf4j
public class LogConsumer {
    @Resource
    MeterRegistry registry;

    @KafkaListener(topics = "${aliyun.kafka.consumer.topic}")
    public void consume(String message) {
        String regex = "(\\S+) - - \\[.*\\] \"(\\S+) (\\S+) HTTP/\\d.\\d\" (\\d{3}|-) (\\d+|-) \"(.*?)\" \"(.*?)\"";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(message);

        if (matcher.matches()) {
            String ip = matcher.group(1);
            String method = matcher.group(2);
            String uri = matcher.group(3);
            String statusCode = matcher.group(4);
            String bytes = matcher.group(5);
            String userAgent = matcher.group(6);
            System.out.println("matched");

            // @see: https://pandaychen.github.io/2020/04/11/PROMETHEUS-METRICS-INTRO/
//            Counter counter = Counter.builder(MeterConst.OSS_ACCESS_LOG)
//                    .tag("uri", uri)
//                    .tag("method", method)
//                    .tag("code", statusCode)
//                    .tag("ip", ip)
//                    .tag("ua", userAgent)
//                    .tag("bytes", bytes)
//                    .register(registry);
//            counter.increment();
            Counter counterForSize = Counter.builder(MeterConst.OSS_ACCESS_SIZE)
                    .tag("uri", uri)
//                    .tag("method", method)
//                    .tag("code", statusCode)
                    .tag("ip", ip)
//                    .tag("ua", userAgent)
//                    .tag("bytes", bytes)
                    .register(registry);
            counterForSize.increment(Double.parseDouble(bytes));
        }
        log.info("message: " + message);
        System.out.println("message: " + message);
    }
}
